package com.ikangtai.shecare.personal;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.Constant;
import com.ikangtai.shecare.common.EnConstant;
import com.ikangtai.shecare.common.al.Algorithm;
import com.ikangtai.shecare.common.al.CycleUnitDS;
import com.ikangtai.shecare.common.al.DayUnitDSInput;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.al.UserUnitDS;
import com.ikangtai.shecare.common.baseView.ListBar;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.baseView.pickerDialog.MyEnInfoPicker;
import com.ikangtai.shecare.common.baseView.pickerDialog.MyInfoPicker;
import com.ikangtai.shecare.common.baseView.pickerDialog.MyInfoPickerDialog;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncHealthInfo;
import com.ikangtai.shecare.common.eventBusMsg.AlgoUpdateMsg;
import com.ikangtai.shecare.common.eventBusMsg.HealthInfoMsg;
import com.ikangtai.shecare.common.httpBean.GetAllTask;
import com.ikangtai.shecare.common.util.ActivityCollector;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.curve.CustomerData;
import com.ikangtai.shecare.curve.WebViewCfg;
import com.ikangtai.shecare.main.MainActivity;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

public class HealthInfoActivity extends BaseActivity implements View.OnClickListener {

    private TopBar topBar;
    private ListBar mensesLen;
    private ListBar periodLen;
    private ListBar mensesRegular;
    private ListBar lastPeriodDate;
    private Button saveButton;
    private int typeBind;
    private int status;
    private static final int STATE_SAVE_FAILURE = 1;
    private static final int STATE_SAVE_SUCCESS = 2;
    private static final int UPLOAD_CYCLE_DATA_OK = 3;
    private static final int UPLOAD_CYCLE_DATA_NOK = 4;
    private static final int UPDATE_TASK_OK = 5;
    private static final int UPDATE_TASK_NOK = 6;
    private static final int CHANGE_AND_UPLOAD_CYCLE_DATA_OK = 7;
    private static final int CHANGE_AND_UPLOAD_CYCLE_DATA_NOK = 8;
    private JSONArray jsonArrayCycleDatas, jsonArrayUserDatas;
    private JSONObject jsonObjectUserData;
    private Algorithm algorithm;
    private DBManager dbManager;
    private int mensesLenValue;
    private int periodLenValue;
    private int mensesTypeValue;
    private String lastPeriodDateValue;
    public static final int MYINFO_INTO = 106;
    public static final int REGISTER_INTO = 107;
    private int maxLen = 55;
    private int alterLen = 5;
    private ProgressDialog progressDialog;
    private WebView webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_personal_health_info);
        ActivityCollector.addActivity(this);
        typeBind = getIntent().getIntExtra("type", MYINFO_INTO);
        if (typeBind == REGISTER_INTO) {
            status = getIntent().getIntExtra("status", 0);
        }
        algorithm = new Algorithm(this);
        dbManager = new DBManager(this);
        EventBus.getDefault().register(this);
        initView();
        initValue();

        if (InternetUtil.hasInternet()) {
            SyncHealthInfo syncHealthInfo = new SyncHealthInfo(this);
            syncHealthInfo.syncHealthInfoWithNetwork();
        }
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        mensesLen = (ListBar) findViewById(R.id.mensesDuration);
        mensesLen.setOnClickListener(this);
        periodLen = (ListBar) findViewById(R.id.mensesPeriod);
        periodLen.setOnClickListener(this);
        mensesRegular = (ListBar) findViewById(R.id.mensesRegular);
        mensesRegular.setOnClickListener(this);
        lastPeriodDate = (ListBar) findViewById(R.id.lastMensesTime);
        lastPeriodDate.setOnClickListener(this);
        saveButton = (Button) findViewById(R.id.healthInfo_save_button);
        saveButton.setOnClickListener(this);
    }

    private void initValue() {

        if (typeBind == MYINFO_INTO) {
            //saveButton.setVisibility(View.GONE);
            //mensesLen.setOnClickListener(null);
            //periodLen.setOnClickListener(null);
            //mensesRegular.setOnClickListener(null);
            lastPeriodDate.setOnClickListener(null);
        } else {
//            new AlertDialog.Builder(this)
//                    .setTitle(R.string.warm_prompt)
//                    .setMessage(R.string.health_info_toast)
//                    .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    })
//                    .create()
//                    .show();
        }

        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                if (0 == App.memory_preference_mensesLen) {
                    mensesLen.setRightText("5" + getResources().getString(R.string.day));
                    mensesLenValue = 5;
                    // dbManager.updateUserPreference(App.userName, "mensesLen", "5", "isHealthInfoSynced",0);
                } else {
                    mensesLenValue = App.memory_preference_mensesLen;
                    mensesLen.setRightText(String.valueOf(App.memory_preference_mensesLen) + getResources().getString(R.string.day));
                }
                if (0 == App.memory_preference_periodLen) {
                    periodLen.setRightText("28" + getResources().getString(R.string.day));
                    periodLenValue = 28;
                    //dbManager.updateUserPreference(App.userName, "periodLen", "28", 0);
                } else {
                    periodLenValue = App.memory_preference_periodLen;
                    periodLen.setRightText(String.valueOf(App.memory_preference_periodLen) + getResources().getString(R.string.day));
                }
                if (2 == App.memory_preference_mensesType) {
                    switch (Locale.getDefault().getLanguage()) {
                        case "zh":
                            mensesRegular.setRightText(MyInfoPicker.regular[0]);
                            break;
                        default:
                            mensesRegular.setRightText(MyEnInfoPicker.regular[0]);
                    }
                    mensesTypeValue = 0;
                    // dbManager.updateUserPreference(App.userName, "mensesType", "0", 0);
                    // App.saveUserPreference("mensesRegular", 0);
                } else {
                    mensesTypeValue = App.memory_preference_mensesType;
                    mensesRegular.setRightText(MyInfoPicker.regular[App.memory_preference_mensesType]);
                }

                if ("".equals(App.memory_preference_lastPeriodDate) || null == App.memory_preference_lastPeriodDate) {
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int monthofYear = calendar.get(Calendar.MONTH);
                    int dayofMonth = calendar.get(Calendar.DAY_OF_MONTH);
                    String dateStr = year + getString(R.string.year) + (monthofYear + 1) + getString(R.string.month) + dayofMonth + getString(R.string.day) + "";
                    String setLastPeriodDate = year + "-" + (monthofYear + 1) + "-" + dayofMonth;

                    lastPeriodDateValue = setLastPeriodDate;
                    lastPeriodDate.setRightText(dateStr);
                } else {
                    String lastPeriodValue = App.memory_preference_lastPeriodDate;
                    String sub[] = lastPeriodValue.split("-");
                    lastPeriodDate.setRightText(sub[0] + getString(R.string.year) + sub[1] + getString(R.string.month) + sub[2] + getString(R.string.day));
                    lastPeriodDateValue = App.memory_preference_lastPeriodDate;
                }
                break;
            default:
                if (0 == App.memory_preference_mensesLen) {
                    mensesLen.setRightText("5");
                    mensesLenValue = 5;
                    // dbManager.updateUserPreference(App.userName, "mensesLen", "5", "isHealthInfoSynced",0);
                } else {
                    mensesLenValue = App.memory_preference_mensesLen;
                    mensesLen.setRightText(String.valueOf(App.memory_preference_mensesLen));
                }
                if (0 == App.memory_preference_periodLen) {
                    periodLen.setRightText("28" + getResources().getString(R.string.day));
                    periodLenValue = 28;
                    //dbManager.updateUserPreference(App.userName, "periodLen", "28", 0);
                } else {
                    periodLenValue = App.memory_preference_periodLen;
                    periodLen.setRightText(String.valueOf(App.memory_preference_periodLen));
                }
                if (2 == App.memory_preference_mensesType) {
                    mensesRegular.setRightText(MyEnInfoPicker.regular[0]);
                    mensesTypeValue = 0;
                    // dbManager.updateUserPreference(App.userName, "mensesType", "0", 0);
                    // App.saveUserPreference("mensesRegular", 0);
                } else {
                    mensesTypeValue = App.memory_preference_mensesType;
                    mensesRegular.setRightText(MyEnInfoPicker.regular[App.memory_preference_mensesType]);
                }

                if ("".equals(App.memory_preference_lastPeriodDate) || null == App.memory_preference_lastPeriodDate) {
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int monthofYear = calendar.get(Calendar.MONTH);
                    int dayofMonth = calendar.get(Calendar.DAY_OF_MONTH);
                    String dateStr = year + (monthofYear + 1) + dayofMonth + "";
                    String setLastPeriodDate = year + "-" + (monthofYear + 1) + "-" + dayofMonth;

                    lastPeriodDateValue = setLastPeriodDate;
                    lastPeriodDate.setRightText(dateStr);
                } else {
                    String lastPeriodValue = App.memory_preference_lastPeriodDate;
                    String sub[] = lastPeriodValue.split("-");
                    lastPeriodDate.setRightText(sub[0] + "-" + sub[1] + "-" + sub[2]);
                    lastPeriodDateValue = App.memory_preference_lastPeriodDate;
                }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.mensesDuration:
                switch (Locale.getDefault().getLanguage()) {
                    case "zh":
                        showInfoPickerDialog(Constant.MENSES_LENGTH);
                        break;

                    default:
                        showInfoPickerDialog(EnConstant.MENSES_LENGTH);
                }

                return;
            case R.id.mensesPeriod:
                switch (Locale.getDefault().getLanguage()) {
                    case "zh":
                        showInfoPickerDialog(Constant.PERIOD_LENGTH);
                        break;
                    default:
                        showInfoPickerDialog(EnConstant.PERIOD_LENGTH);

                }
                return;
            case R.id.mensesRegular:
                switch (Locale.getDefault().getLanguage()) {
                    case "zh":
                        showInfoPickerDialog(Constant.MENSES_REGULAR);
                        break;
                    default:
                        showInfoPickerDialog(EnConstant.MENSES_REGULAR);
                }
                return;
            case R.id.lastMensesTime:
                setDateDialog();
                return;
            case R.id.healthInfo_save_button:
                if (typeBind == MYINFO_INTO) {
                    if (mensesLenValue != App.memory_preference_mensesLen || periodLenValue != App.memory_preference_periodLen || mensesTypeValue != App.memory_preference_mensesType) {
                        showProgressDialog();
                        AppLog.e("changeAndUpdateHealthInfo start!");
                        changeAndUpdateHealthInfo();
                    } else {
                        ActivityCollector.finishAll();
                    }

                } else {
                    showProgressDialog();
                    AppLog.e("register and saveHealthInfo start!");
                    saveHealthInfo();
                }

            default:
                return;
        }

    }

    private void changeAndUpdateHealthInfo() {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "user/registerUserInfo.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("status", App.status);
            if (null != App.memory_preference_birthday)
                okHttpClient.add("birthday", App.memory_preference_birthday);
            else
                okHttpClient.add("birthday", "2000-1-1");
            okHttpClient.add("mensesLen", mensesLenValue);
            okHttpClient.add("periodLen", periodLenValue);
            okHttpClient.add("mensesType", mensesTypeValue);
            okHttpClient.add("lastPeriodDate", lastPeriodDateValue);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    saveChangedHealthInfo2Local(0);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        String str = response.body().string();
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            saveChangedHealthInfo2Local(1);

                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            changeAndUpdateHealthInfo();
                        } else {
                            saveChangedHealthInfo2Local(0);
                        }
                    } catch (JSONException e) {
                        AppLog.i("upload registerUserInfo onResponse failed!");
                        e.printStackTrace();
                        saveChangedHealthInfo2Local(0);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("registerUserInfo exception!");
            saveChangedHealthInfo2Local(0);
        }
    }

    private void saveChangedHealthInfo2Local(int isSynced) {
        if (mensesLenValue != App.memory_preference_mensesLen || periodLenValue != App.memory_preference_periodLen) {
            saveHealthInfo2SQL(isSynced);
            changeAndUpdateALgorithmData(isSynced);
        } else {
            saveHealthInfo2SQL(isSynced);
            sendResp(CHANGE_AND_UPLOAD_CYCLE_DATA_NOK);
        }

    }

    private void changeAndUpdateALgorithmData(int isSynced) {
        UserUnitDS userData = new UserUnitDS();
        userData.averageMenstruationLength = Float.parseFloat(mensesLen.getRightText().replace(getResources().getString(R.string.day), ""));
        userData.averageCycleLength = Float.parseFloat(periodLen.getRightText().replace(getResources().getString(R.string.day), ""));
        long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime()/1000);
        int result = algorithm.chgHealthInfoAL(algorithm.getModifyHealthInfoMensesInput(currentDayCycleUnitDSMensesStartConfirm), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), userData, isSynced);
        if(result == 234) g1Tog2Algorithm();
        jsonArrayCycleDatas = algorithm.getCycleOutputJson();
        jsonArrayUserDatas = algorithm.getDayOutputJson();
        jsonObjectUserData = algorithm.getUserInfoJson();
        uploadChangedCycleData();
    }

    //算法返回值为234时调用一代转二代
    private void g1Tog2Algorithm(){
        UserUnitDS userData = new UserUnitDS();
        userData.averageMenstruationLength = App.memory_preference_mensesLen;
        userData.averageCycleLength = App.memory_preference_periodLen;
        DayUnitDSInput[] dayInput = dbManager.getDayInputListFromG1Record(App.userName);
        algorithm.g1FirstLoginG2(userData, dayInput, 0);
        checkIfNeedDealHistoryData();
    }

    private void checkIfNeedDealHistoryData() {
        CycleUnitDS[] cycleUnitDSes = dbManager.getALCycleOutput(App.userName, null);
        if(null != cycleUnitDSes && cycleUnitDSes.length > 0){
            for(int i = 0; i < cycleUnitDSes.length; i++){
                cycleUnitDSes[i].ovulationDayUserRecordBasis = -99;
            }
            dbManager.saveALCycleOutput(cycleUnitDSes, 0);
        }

        List<DayUnitDSOutput> dayUnitDSOutputs = dbManager.getALDayUnitDSOutputList(App.userName);
        if(null != dayUnitDSOutputs && dayUnitDSOutputs.size() > 0){
            for(int i = 0; i < dayUnitDSOutputs.size(); i++){
                dayUnitDSOutputs.get(i).periodAchieveForecast = 99;
            }
            dbManager.saveALDayOutput(dayUnitDSOutputs, 0);
        }
        saveALResult2Sqlite(0);
    }

    private void uploadChangedCycleData() {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas.toString());
            AppLog.i("userData = " + jsonArrayUserDatas.toString());
            AppLog.i("userInfo = " + jsonObjectUserData.toString());
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("cycleData", jsonArrayCycleDatas);
            okHttpClient.add("userData", jsonArrayUserDatas);
            okHttpClient.add("userInfo", jsonObjectUserData);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    saveALResult2Sqlite(0);
                    sendResp(CHANGE_AND_UPLOAD_CYCLE_DATA_NOK);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            sendResp(CHANGE_AND_UPLOAD_CYCLE_DATA_OK);
                            AppLog.i("UploadCycleData onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            uploadChangedCycleData();
                        } else {
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                            saveALResult2Sqlite(0);
                            sendResp(CHANGE_AND_UPLOAD_CYCLE_DATA_NOK);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        saveALResult2Sqlite(0);
                        sendResp(CHANGE_AND_UPLOAD_CYCLE_DATA_NOK);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();
            saveALResult2Sqlite(0);
            sendResp(CHANGE_AND_UPLOAD_CYCLE_DATA_NOK);
        }
    }

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.saving));
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void setProgressDialogMsg(String message) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.setMessage(message);
        }

    }

    private void dissmissProgressDiaLog() {
        (new Handler()).postDelayed(new Runnable() {
            @Override
            public synchronized void run() {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                ActivityCollector.finishAll();
            }
        }, 2500);
    }

    private void showInfoPickerDialog(final String dialogTitle) {
        MyInfoPickerDialog myInfoDialog = new MyInfoPickerDialog(HealthInfoActivity.this, dialogTitle);
        myInfoDialog.setOnBrandSetListener(new MyInfoPickerDialog.OnBrandSetListener() {
            @Override
            public void OnBrandSet(AlertDialog dialog, String brand) {

                switch (Locale.getDefault().getLanguage()) {
                    case "zh":
                        if (dialogTitle.equals(Constant.MENSES_LENGTH)) {
                            mensesLen.setRightText(brand);
                            mensesLenValue = Integer.valueOf(brand);
                            // dbManager.updateUserPreference(App.userName, "mensesLen", String.valueOf(Integer.valueOf(brand)), 0);
                        } else if (dialogTitle.equals(Constant.PERIOD_LENGTH)) {
                            periodLen.setRightText(brand);
                            periodLenValue = Integer.valueOf(brand);
                            // dbManager.updateUserPreference(App.userName, "periodLen", String.valueOf(Integer.valueOf(brand)), 0);
                        } else if (dialogTitle.equals(Constant.MENSES_REGULAR)) {
                            mensesRegular.setRightText(brand);
                            if (brand.equals(MyInfoPicker.regular[0])) {
                                mensesTypeValue = 0;
                                // dbManager.updateUserPreference(App.userName, "mensesType", String.valueOf(0), 0);
                            } else if (brand.equals(MyInfoPicker.regular[1])) {
                                mensesTypeValue = 1;
                                //dbManager.updateUserPreference(App.userName, "mensesType", String.valueOf(1), 0);
                            }
                        }
                        break;
                    default:
                        if (dialogTitle.equals(EnConstant.MENSES_LENGTH)) {
                            mensesLen.setRightText(brand);
                            mensesLenValue = Integer.valueOf(brand);
                            // dbManager.updateUserPreference(App.userName, "mensesLen", String.valueOf(Integer.valueOf(brand)), 0);
                        } else if (dialogTitle.equals(EnConstant.PERIOD_LENGTH)) {
                            periodLen.setRightText(brand);
                            periodLenValue = Integer.valueOf(brand);
                            // dbManager.updateUserPreference(App.userName, "periodLen", String.valueOf(Integer.valueOf(brand)), 0);
                        } else if (dialogTitle.equals(EnConstant.MENSES_REGULAR)) {
                            mensesRegular.setRightText(brand);
                            if (brand.equals(MyInfoPicker.regular[0])) {
                                mensesTypeValue = 0;
                                // dbManager.updateUserPreference(App.userName, "mensesType", String.valueOf(0), 0);
                            } else if (brand.equals(MyInfoPicker.regular[1])) {
                                mensesTypeValue = 1;
                                //dbManager.updateUserPreference(App.userName, "mensesType", String.valueOf(1), 0);
                            }
                        }
                }

            }
        });
        myInfoDialog.setCancelable(false);
        myInfoDialog.show();
    }

    private void setDateDialog() {

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int monthofYear = calendar.get(Calendar.MONTH);
        int dayofMonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String dateStr = year + getString(R.string.year) + (monthOfYear + 1) + getString(R.string.month) + dayOfMonth + getString(R.string.day) + "";
                if (DateUtil.isFutureDate(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth)) {
                    Toast.makeText(HealthInfoActivity.this, R.string.future_time, Toast.LENGTH_SHORT).show();
                } else {
                    lastPeriodDate.setRightText(dateStr);
                    String setLastPeriodDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                    //dbManager.updateUserPreference(App.userName, "lastPeriodDate", setLastPeriodDate);
                    lastPeriodDateValue = setLastPeriodDate;
                }
            }
        }, year, monthofYear, dayofMonth);
        dialog.setCancelable(false);
        DatePicker datePicker = dialog.getDatePicker();
        datePicker.setMaxDate(new Date().getTime());
        //datePicker.setMinDate(new Date().getTime());
        dialog.show();

    }

    private void saveHealthInfo() {


        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "user/registerUserInfo.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("status", App.status);
            okHttpClient.add("birthday", "2000-1-1");
            okHttpClient.add("mensesLen", mensesLenValue);
            okHttpClient.add("periodLen", periodLenValue);
            okHttpClient.add("mensesType", mensesTypeValue);
            okHttpClient.add("lastPeriodDate", lastPeriodDateValue);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                        @Override
                        public void onFailure(Request request, IOException e) {
                            super.onFailure(request, e);
                            saveHealthInfo2Local(0);
                        }

                        @Override
                        public void onResponse(Response response) throws IOException {

                            try {
                                String str = response.body().string();
                                JSONObject respJSONObj = new JSONObject(str);
                                int respCode = respJSONObj.getInt("code");

                                if (200 == respCode) {
                                    saveHealthInfo2SQL(1);

                                    dbManager.updateUserPreference(App.userName, "lastPeriodDate", lastPeriodDateValue);
                                    App.memory_preference_lastPeriodDate = lastPeriodDateValue;


                                    if (typeBind == REGISTER_INTO) {
                                        saveLastPeriodRecord();
                                        initALgorithmData();
                                    }

                                    HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
                                    healthInfoMsg.setRespCode(App.HTTP_RESP_OK);

                                    if (getAllTask()) {
                                        EventBus.getDefault().post(healthInfoMsg);
                                    }
                                } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                                    OKHttpUtil.setNewToken();
                                    saveHealthInfo();
                                } else {
                                    saveHealthInfo2Local(0);
                                }
                            } catch (JSONException e) {
                                AppLog.i("upload registerUserInfo onResponse failed!");
                                e.printStackTrace();
                                saveHealthInfo2Local(0);
                            }
                        }
                    }

            );
        } catch (JSONException e) {
            AppLog.i("registerUserInfo exception!");
            saveHealthInfo2Local(0);
        }
    }

    private void saveLastPeriodRecord() {
        UserRecordData userRecordData = new UserRecordData();
        userRecordData.setId(UUID.randomUUID().toString());
        userRecordData.setRecordDate(DateUtil.getStringToDate(lastPeriodDateValue + " 12:00:00"));
        userRecordData.setMensesInfo(1);
        userRecordData.setUserName(App.userName);
        dbManager.saveRecordData(userRecordData);
    }

    private void saveHealthInfo2Local(int isSynced) {
        saveHealthInfo2SQL(isSynced);

        if (typeBind == REGISTER_INTO) {
            saveLastPeriodRecord();
            initALgorithmData();
        }

        HealthInfoMsg healthInfoMsg = new HealthInfoMsg();

        int respCode = (isSynced == 1 ? App.HTTP_RESP_OK : App.HTTP_RESP_FAIL);
        healthInfoMsg.setRespCode(respCode);

        EventBus.getDefault().post(healthInfoMsg);
    }

    /**
     * 上传默认taskID值“1,2,3”
     */
    private void postUpdateTaskIDs() {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "care/updateTaskID.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("taskIDs", "1,2,3");
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
                    healthInfoMsg.setRespCode(UPDATE_TASK_NOK);
                    EventBus.getDefault().post(healthInfoMsg);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            dbManager.updateUserPreference(App.userName, "taskIDs", "1,2,3", "isDataDownloaded", 1);//更新数据库数据
                            healthInfoMsg.setRespCode(UPDATE_TASK_OK);
                            AppLog.i("update task ids onResponse success!");
                            EventBus.getDefault().post(healthInfoMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            postUpdateTaskIDs();
                        } else {
                            healthInfoMsg.setRespCode(UPDATE_TASK_NOK);
                            AppLog.i("update task ids onResponse respCode failed! is:" + respCode);
                            EventBus.getDefault().post(healthInfoMsg);
                        }
                    } catch (JSONException e) {
                        AppLog.i("update task ids onResponse failed!");
                        healthInfoMsg.setRespCode(UPDATE_TASK_NOK);
                        e.printStackTrace();
                        EventBus.getDefault().post(healthInfoMsg);
                    }
                }
            });
        } catch (JSONException e) {
            HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
            healthInfoMsg.setRespCode(UPDATE_TASK_NOK);
            EventBus.getDefault().post(healthInfoMsg);
            e.printStackTrace();
        }
    }

    private void initALgorithmData() {
        UserUnitDS userData = new UserUnitDS();
        userData.averageMenstruationLength = Float.parseFloat(mensesLen.getRightText().replace(getResources().getString(R.string.day), ""));
        userData.averageCycleLength = Float.parseFloat(periodLen.getRightText().replace(getResources().getString(R.string.day), ""));
        algorithm.firstExecAL(userData, DateUtil.getDateZeroTime2bit(getStringToDate(lastPeriodDate.getRightText()) / 1000));
        jsonArrayCycleDatas = algorithm.getCycleOutputJson();
        jsonArrayUserDatas = algorithm.getDayOutputJson();
        jsonObjectUserData = algorithm.getUserInfoJson();
    }

    private void saveALResult2Sqlite(int isSynced) {
        algorithm.saveALData2Sqlite(isSynced);
    }

    /* 将字符串转为时间戳 */
    private long getStringToDate(String time) {
        SimpleDateFormat sf = null;
        sf = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date();
        try {
            date = sf.parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }

    @Subcriber
    private void dealHealthInfoMsg(HealthInfoMsg healthInfoMsg) {

        int respCode = healthInfoMsg.getRespCode();
        switch (respCode) {
            case App.HTTP_RESP_OK:
                if (typeBind == REGISTER_INTO)
                    UploadCycleData();
                break;
            case App.HTTP_RESP_FAIL:
                Toast.makeText(getApplicationContext(), R.string.save_fail, Toast.LENGTH_SHORT).show();
                break;
            case STATE_SAVE_SUCCESS:
                Toast.makeText(getApplicationContext(), R.string.save_success, Toast.LENGTH_SHORT).show();
                postUpdateTaskIDs();
                break;
            case STATE_SAVE_FAILURE:
                Toast.makeText(getApplicationContext(), R.string.stats_fail, Toast.LENGTH_SHORT).show();
                break;
            case UPLOAD_CYCLE_DATA_OK:
                saveStatus();
                initDayUnitDSOutputsListIntoMemory();
                break;
            case UPLOAD_CYCLE_DATA_NOK:
                Toast.makeText(getApplicationContext(), R.string.upload_failed, Toast.LENGTH_SHORT).show();
                initDayUnitDSOutputsListIntoMemory();
                break;
            case UPDATE_TASK_OK:
                AppLog.i("update task ids onResponse success!");
                setDataDownloaded();

                if (App.dayUnitDSOutputsList.size() != 0)
                    initWebview();

                getInMainActivity();
                break;
            case UPDATE_TASK_NOK:
                AppLog.i("update task ids onResponse failed!");
                break;
            case CHANGE_AND_UPLOAD_CYCLE_DATA_OK:
                initDayUnitDSOutputsListIntoMemory();
                AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
                algoUpdateMsg.setRespCode(1);
                EventBus.getDefault().post(algoUpdateMsg);
                setProgressDialogMsg(getString(R.string.save_success));
                dissmissProgressDiaLog();
                break;
            case CHANGE_AND_UPLOAD_CYCLE_DATA_NOK:
                initDayUnitDSOutputsListIntoMemory();
                AlgoUpdateMsg algoUpdateMsg1 = new AlgoUpdateMsg();
                algoUpdateMsg1.setRespCode(1);
                EventBus.getDefault().post(algoUpdateMsg1);
                setProgressDialogMsg(getString(R.string.save_success));
                dissmissProgressDiaLog();
                break;
            default:
                break;
        }
    }

    private void initWebview() {
        webview = (WebView) findViewById(R.id.webview);
        WebViewCfg webViewCfg = new WebViewCfg(webview);
        webview = webViewCfg.getCfgedWebView(this, false);

        AppLog.i("hxiao LoginActivity initData.html");
        webview.addJavascriptInterface(new CustomerData(this, App.userName), "CustomerData");
        webview.loadUrl("file:///android_asset/health/initData.html");
    }

    private void initDayUnitDSOutputsListIntoMemory() {
        dbManager.initDayUnitDSOutputsList2Memory(App.userName);
    }

    private void setDataDownloaded() {
        dbManager.updateUserPreference(App.userName, "isDataDownloaded", "true");
    }

    private void getInMainActivity() {


        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;


            Intent intent = new Intent(HealthInfoActivity.this, MainActivity.class);
            startActivity(intent);
            ActivityCollector.finishAll();
        }
    }

    private void saveHealthInfo2SQL(int isSynced) {

        ArrayList<String> columnNames = new ArrayList<String>();
        columnNames.add("mensesLen");
        columnNames.add("periodLen");
        columnNames.add("mensesType");
        columnNames.add("lastPeriodDate");

        ArrayList<String> columnValues = new ArrayList<String>();
        columnValues.add(String.valueOf(mensesLenValue));
        columnValues.add(String.valueOf(periodLenValue));
        columnValues.add(String.valueOf(mensesTypeValue));
        columnValues.add(lastPeriodDateValue);

        dbManager.updateUserPrefList(App.userName, columnNames, columnValues, "isHealthInfoSynced", isSynced);

        App.memory_preference_mensesLen = mensesLenValue;
        App.memory_preference_periodLen = periodLenValue;
        App.memory_preference_mensesType = mensesTypeValue;
        App.memory_preference_lastPeriodDate = lastPeriodDateValue;
    }

    private void UploadCycleData() {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas.toString());
            AppLog.i("userData = " + jsonArrayUserDatas.toString());
            AppLog.i("userInfo = " + jsonObjectUserData.toString());
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("cycleData", jsonArrayCycleDatas);
            okHttpClient.add("userData", jsonArrayUserDatas);
            okHttpClient.add("userInfo", jsonObjectUserData);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    sendResp(UPLOAD_CYCLE_DATA_NOK);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            saveALResult2Sqlite(1);
                            sendResp(UPLOAD_CYCLE_DATA_OK);
                            AppLog.i("UploadCycleData onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            UploadCycleData();
                        } else {
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                            sendResp(UPLOAD_CYCLE_DATA_NOK);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        sendResp(UPLOAD_CYCLE_DATA_NOK);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();

            sendResp(UPLOAD_CYCLE_DATA_NOK);
        }
    }

    private void sendResp(int state) {
        HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
        healthInfoMsg.setRespCode(state);
        EventBus.getDefault().post(healthInfoMsg);
    }

    private void saveStatus() {
        AppLog.i("save status! status = " + App.status + ", auth token! token = " + App.authToken);
        OKHttpUtil okHttpClient = new OKHttpUtil(this);

        String appendUrl = "care/switchingStatus.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("status", App.status);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    AppLog.i("save status failed! request = " + request.urlString());
                    HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
                    healthInfoMsg.setRespCode(STATE_SAVE_FAILURE);
                    EventBus.getDefault().post(healthInfoMsg);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("save status onResponse success!");
                            dbManager.updateUserPreference(App.userName, "state", String.valueOf(App.status), "isStateSynced", 1);
                            App.memory_preference_userState = App.status;
                            App.saveUserPreference("bindType", "bindThermometer");

                            HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
                            healthInfoMsg.setRespCode(STATE_SAVE_SUCCESS);
                            EventBus.getDefault().post(healthInfoMsg);
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            OKHttpUtil.setNewToken();
                            saveStatus();
                        } else {
                            AppLog.i("save status onResponse failed! respCode is:" + respCode);
                            HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
                            healthInfoMsg.setRespCode(STATE_SAVE_FAILURE);
                            EventBus.getDefault().post(healthInfoMsg);
                        }
                    } catch (JSONException e) {
                        AppLog.i("save status onResponse failed!");
                        e.printStackTrace();
                        HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
                        healthInfoMsg.setRespCode(STATE_SAVE_FAILURE);
                        EventBus.getDefault().post(healthInfoMsg);
                    }
                }

            });
        } catch (JSONException e) {
            AppLog.i("save status JSONException!");
            e.printStackTrace();
            HealthInfoMsg healthInfoMsg = new HealthInfoMsg();
            healthInfoMsg.setRespCode(STATE_SAVE_FAILURE);
            EventBus.getDefault().post(healthInfoMsg);
        }
    }


    private Boolean getAllTask() {

        OKHttpUtil okHttpUtil = new OKHttpUtil(this);
        String appendUrl = "task/getAllTask.json";
        try {
            okHttpUtil.add("authToken", App.authToken);
            okHttpUtil.add("language", "ch");
            okHttpUtil.postAsync(appendUrl, okHttpUtil.new BaseCallBack() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            super.onFailure(request, e);
                        }

                        @Override
                        public void onResponse(Response response) throws IOException {
                            String respStr = response.body().string();

                            try {
                                JSONObject respJSONObj = new JSONObject(respStr);
                                int respCode = respJSONObj.getInt("code");

                                if (App.HTTP_RESP_OK == respCode) {
                                    GetAllTask getAllTask = JSON.parseObject(respStr, GetAllTask.class);
                                    if (getAllTask != null) {

                                        dbManager.initTaskDetail(1, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(0).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(0).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "基础体温", "BBT",
                                                "48c3fc", "3DB4F9", 2, 6, 8, 11, getAllTask.getSysTask().get(1).getDate(), "测量基础体温", "Measure BBT ");

                                        dbManager.initTaskDetail(2, App.userName, 1, 1, "", "", "", "",
                                                "", "1178E7", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "饮水6-8杯", "6-8 glasses of water");

                                        dbManager.initTaskDetail(3, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(2).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                getAllTask.getSysTask().get(2).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "叶酸", "Folic Acid",
                                                "8F40DE", "8F40DE", 2, 4, 5, 15, getAllTask.getSysTask().get(2).getDate(), "服用叶酸", "Take Folic Acid");

                                        dbManager.initTaskDetail(4, App.userName, 1, 1, "", "", "", "",
                                                "", "9A7EE3", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "健身运动", "Working out");

                                        dbManager.initTaskDetail(5, App.userName, 1, 1, "", "",
                                                "", "", "", "41CF74", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "吃水果", "Daily Fruits");

                                        dbManager.initTaskDetail(6, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(5).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(5).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "宫颈粘液", "Cervical Mucus",
                                                "cf7edd", "C363D5", 2, 6, 6, 20, getAllTask.getSysTask().get(1).getDate(), "观察宫颈粘液", "Check Cervical Mucus");
                                        dbManager.initTaskDetail(7, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(6).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(6).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "排卵试纸", "Test",
                                                "85CC54", "F9575C", 2, 6, 10, 14, getAllTask.getSysTask().get(1).getDate(), "测试排卵试纸", "Ovulation Test");
                                        dbManager.initTaskDetail(8, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(7).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(7).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "B超", "Ultrasound",
                                                "F6BE3A", "FDB50A", 0, 2, 0, 10, getAllTask.getSysTask().get(1).getDate(), "B超检查", "Ultrasound Examination");
                                    } else {
//
                                    }
                                } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT)

                                {
                                    OKHttpUtil.setNewToken();
                                    getAllTask();
                                } else

                                {
                                    AppLog.i("error code! code = " + respCode);
                                }
                            } catch (
                                    JSONException e
                                    )

                            {
                                AppLog.i("JSONException e");
                                e.printStackTrace();
                            }
                        }
                    }

            );
        } catch (
                JSONException e
                )

        {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
